import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/student'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}
// initial state
const state = getDefaultState()
// actions
const actions = {
  // student login
  login ({ commit }, loginForm) {
    const { email, password, image_code_id, image_code } = loginForm
    return new Promise((resolve, reject) => {
      login({
        email: email.trim(),
        password: password,
        image_code: image_code,
        image_code_id: image_code_id
      })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token) // 设置token
          // commit('SET_AVATAR', data.avatar) // 设置头像, 留给获取学生信息时设置
          // commit('SET_NAME', data.nick_name)
          setToken(data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // 清空token
      commit('RESET_STATE')
      resolve()
    })
  },
  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  },
  // get student info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data } = response
          if (!data) {
            return reject(new Error('Verification failed, please Login again.'))
          }
          const { nick_name, avatar } = data
          commit('SET_NAME', nick_name)
          commit('SET_AVATAR', avatar)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

// mutations
const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
